'use strict';

const db = uniCloud.database();
const uniIdCommon = require('uni-id-common');

exports.main = async (event, context) => {
  // 1. 获取 token
  const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken);
  if (!token) {
    return { code: 401, msg: '未登录' };
  }
  // 2. 解析 token
  const uniId = uniIdCommon.createInstance({ context });
  const tokenRes = await uniId.checkToken(token);
  if (tokenRes.code !== 0) {
    return { code: 401, msg: 'token无效或已过期' };
  }
  const uid = tokenRes.uid;
  // 3. 查询用户信息
  const userRes = await db.collection('uni-id-users').doc(uid).get();
  if (!userRes.data || userRes.data.length === 0) {
    return { code: 404, msg: '用户不存在' };
  }
  return {
    code: 200,
    data: userRes.data[0]
  };
}; 